//
//  NetworkingTool.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/14.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "NetworkingTool.h"
#import "SQLiteManager.h"
#import "JKDateTool.h"
#import "Reachability.h"
#import "JKProgressHUD.h"

@interface NetworkingTool ()
@property (nonatomic,strong) Reachability *reach;
@end

@implementation NetworkingTool

static NetworkingTool  *_instance;

JKSingleton_M(NetworkingTool)

+ (instancetype)sharedNetworkingTool {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 注意：baseUrl后面一定要写上斜线 /
        NSURL *baseURL = [NSURL URLWithString:@"http://news-at.zhihu.com/api/4/"];
        
        _instance = [[self alloc] initWithBaseURL:baseURL sessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        
        // AFN默认是不支持解析text/plain的，需要自己添加
        _instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"application/json", @"text/json", @"text/javascript", nil];
        
        // 设置请求超时时间
        _instance.requestSerializer.timeoutInterval = 15;
    });
    return _instance;
}

/** 网络请求 */
- (void)loadDataWithUrl:(NSString *)url parameters:(NSDictionary *)parameters finishedBlock:(void(^)(id responseObj, NSError * error))finished{
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    [self GET:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (responseObject == nil) {
            finished(nil, [NSError errorWithDomain:@"jkdev123cool" code:1000 userInfo:@{@"message" : @"没有获取到数据"}]);
            [JKProgressHUD showErrorWithStatus:@"没有获取到数据！"];
            return;
        }
        !finished ? : finished(responseObject, nil);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        !finished ? : finished(nil, error);
        [JKProgressHUD showErrorWithStatus:@"您的网络貌似有点问题~~"];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    }];
}
@end
